﻿using ComLib.ComType;
using ComUIControl;
using CoreBroker;
using KWindow.KPageCore;
using LogLib;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace IPCPages
{
    public partial class PageDetectPhoto : PageControlBase
    {
        private IDCardAll _cardInfo = null;
        private Taker _taker = null;
        private PictureBox pictureBoxDetecting = null;
        public PageDetectPhoto()
        {
            InitializeComponent();
            SetProcessBase(ProcessDetectPhoto.Instance);
        }

        private void GetControls()
        {
            pictureBoxDetecting = GetControl<PictureBox>("pictureBoxDetecting") as PictureBox;         
            labelCountdown = GetControl<Label>("labelCountdown") as Label;
            labelProgress = GetControl<Label>("labelProgress") as Label;
            labelRemind = GetControl<Label>("labelRemind") as Label;
        }

        //初始化窗体数据
        public override void InitCtrls()
        {
            base.InitCtrls();
            GetControls();           
        }

        public override void InitData()
        {
            base.InitData();
            _taker = Process.GetValue<Taker>("Taker");
            if(_taker != null)
            {
                _taker.AddTakingCompletedEvent(OnTakingCompletedReported);
            }
            _cardInfo = Process.GetValue<IDCardAll>("IDCardInfo");
            RemindSecond = 60;           
        }

        public override void ClearData()
        {
            base.ClearData();        
            if (_taker != null)
            {
                _taker.ClearData();
            }
            _taker = null;
        }

        protected void OnTakingCompletedReported(object sender, TakingCompletedEventArgs e)
        {
            if (this.InvokeRequired)
            {
                TakingCompletedEventHandler handler
                    = new TakingCompletedEventHandler(OnTakingCompletedReported);
                this.Invoke(handler, new object[] { sender, e });
                return;
            }       
            int successCount = 0;
            foreach (TakingResult res in e.Results)
            {
                if (res.Success)
                {
                    successCount++;
                }
            }
            PhotoTakenResult flag = PhotoTakenResult.Failed;
            // 拍照成功
            if (successCount == PhotosCount)
            {
                flag = PhotoTakenResult.Success;
                Process.SetValue("PhotoTakenResult", flag);
                OnPhotoTakenSuccess(e);
            }
            // 有一部分失败
            else if (successCount > 0 && successCount < PhotosCount)
            {
                flag = PhotoTakenResult.SomeFailed;
                Process.SetValue("PhotoTakenResult", flag);
                OnSomeoneFailed(e);
            }
            // 全部失败
            else if (successCount == 0)
            {
                Log.WriteAsync($"OnTakingCompletedReported all fail:{flag}, Results.Count={e.Results.Count}");
                flag = PhotoTakenResult.Failed;
                Process.SetValue("PhotoTakenResult", flag);
                OnPhotoTakenFailed(e);
            }
        }

        private void OnPhotoDetecting()
        {
            if (this.InvokeRequired)
            {
                Action outdelegate = new Action(OnPhotoDetecting);
                this.Invoke(outdelegate, new object[] { });
                return;
            }
            ShowRemindCountdownTip();
        }

        public override void StartWork()
        {
            base.StartWork();
            OnPhotoDetecting();
        }

        public override void StopWork()
        {
            Log.WriteAsync($"{this.Name} StopWork.");
            base.StopWork();
            if (timer1.Enabled)
            {
                timer1.Stop();
            }           
        }

        private void OnPlayerAborted(object sender, PlayingAbortEventArgs e)
        {
            MsgBox.Show("镜头运行发生了错误:\n" + e.Error);
        }

        private void OnTakenCompleted()
        {

        }

        private void OnPhotoTakenFailed(TakingCompletedEventArgs e)
        {
            List<TakenPhoto> NoPassPhotos = new List<TakenPhoto>();
            List<TakingResult> results = e.Results;
            for (int i = 0; i < results.Count; i++)
            {
                TakenPhoto photo = results[i].Photo;
                NoPassPhotos.Add(photo);
                Log.WriteAsync($"第{i + 1}张照片的地址: {photo.DestImagePath}, 不合格原因:{photo.NotPassReason}");
            }
            if (_cardInfo != null)
            {
                Log.WriteAsync($"{_cardInfo.number}拍摄的照片全部不合格，NoPassPhotos Count:{NoPassPhotos.Count}.");
            }
            else
            {
                Log.WriteAsync($"照片全部不合格, NoPassPhotos Count:{NoPassPhotos.Count}.");
            }        
            Process.SetValue("NoPassPhotos", NoPassPhotos);
            StopWork();
            ClearData();
            Process.ToAny("IPCPages.PageDetectNoPass");
        }

        private void OnPhotoTakenSuccess(TakingCompletedEventArgs e)
        {
            if(_cardInfo != null)
            {
                Log.WriteAsync($"{_cardInfo.number}拍摄的两张照片全部合格.");
            }
            else
            {
                Log.WriteAsync($"两张照片全部合格.");
            }
            List<TakenPhoto> listTakenPhotos = new List<TakenPhoto>();
            List<TakingResult> results = e.Results;
            for (int i = 0; i < results.Count; i++)
            {
                TakenPhoto photo = results[i].Photo;
                if (results[i].Success)
                {
                    listTakenPhotos.Add(photo);
                    Log.WriteAsync($"第{i+1}张照片的地址: {photo.DestImagePath}");
                }
            }
            StopWork();
            ClearData();
            Process.SetValue("TakenPhotos", listTakenPhotos);
            Process.ToAny("IPCPages.PagePickoutPhoto");
        }

        /// <summary>
        /// 同时存在拍照成功和失败的情况。
        /// 例如当某一张照片检测不通过或者拍照失败时
        /// 展示给用户拍照失败的原因
        /// 进入选照片选择重拍，或者放弃拍照结束流程
        /// </summary>
        /// <param name="e"></param>
        private void OnSomeoneFailed(TakingCompletedEventArgs e)
        {
            if (_cardInfo != null)
            {
                Log.WriteAsync($"{_cardInfo.number}拍摄的两张照片只有一张合格.");
            }
            else
            {
                Log.WriteAsync($"两张照片只有一张合格.");
            }
            List<TakenPhoto> listTakenPhotos = new List<TakenPhoto>();
            List<TakenPhoto> listNoPassPhotos = new List<TakenPhoto>();
            List<TakingResult> results = e.Results;
            for (int i = 0; i < results.Count; i++)
            {
                TakenPhoto photo = results[i].Photo;
                if (results[i].Success)
                {
                    listTakenPhotos.Add(photo);
                    Log.WriteAsync($"第{i + 1}张照片检测合格: {photo.DestImagePath}");
                }
                else
                {
                    listNoPassPhotos.Add(photo);
                    Log.WriteAsync($"第{i + 1}张照片检测不合格: {photo.DestImagePath}，原因:{photo.NotPassReason}");
                }
            }
            Process.SetValue("TakenPhotos", listTakenPhotos);
            Process.SetValue("NoPassPhotos", listNoPassPhotos);
            StopWork();
            ClearData();
            Process.ToAny("IPCPages.PagePickoutPhoto");
        }

        #region 检测倒计时提示
        private int RemindSecond = 60;      
        private Label labelCountdown = null;
        private Label labelRemind = null;
        private Label labelProgress = null;
       
        private void ShowRemindCountdownTip()
        {
            labelCountdown.Visible = true;
            labelProgress.Visible = true;
            labelRemind.Visible = true;
            timer1.Start();
        }

        private void timer1_Tick(object sender, System.EventArgs e)
        {
            if (RemindSecond == 0)
            {
                timer1.Stop();
            }
            if (RemindSecond > 0)
            {
                RemindSecond--;
                labelCountdown.Text = RemindSecond.ToString();
                int left = (this.Width - labelCountdown.Width) / 2;
                labelCountdown.Location = new Point(left, labelCountdown.Top);
            }
        }
        #endregion
    }
}
